package com.metaverse.backend.utils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.beans.Transient;
import java.util.Date;

/**
 * Created by PaperCut on 2018/7/17.
 */
@ApiModel(value = "BusiResult", description = "BusiResult")
public class BusiResult<T> {
    @ApiModelProperty(value = "code")
    private int code = HttpStatus.SUCCESS;

    @ApiModelProperty(value = "msg")
    private String msg = "操作成功";

    @ApiModelProperty(value = "数据")
    private T data;

    @ApiModelProperty(value = "时间")
    private Date timestamp = new Date();

    public BusiResult(){}

    public BusiResult(T data) {
        this.data = data;
    }


    public BusiResult(int code, String message){
        this.code = code;
        this.msg = message;
    }

    public BusiResult(int code, String msg, T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <T> BusiResult<T> success() {
        return success(null);
    }

    public static <T> BusiResult<T> success(T data) {
        return success("操作成功", data);
    }

    public static <T> BusiResult<T> success(String message, T data) {
        return build(HttpStatus.SUCCESS, message, data);
    }

    public static <T> BusiResult<T> fail(String message) {
        return fail(HttpStatus.BAD_REQUEST, message);
    }

    public static <T> BusiResult<T> fail(int code) {
        return fail(code, null);
    }

    public static <T> BusiResult<T> fail(int code, String message) {
        return fail(code, message, null);
    }

    public static <T> BusiResult<T> fail(int code, String message, T data) {
        return build(code, message, data);
    }

    private static <T> BusiResult<T> build(int code, String message, T data) {
        return new BusiResult<>(code, message, data);
    }

    @Transient
    public boolean isSuccess(){
        return this.code == HttpStatus.SUCCESS;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    /**
     * 错误信息
     * @return
     */
    @ApiModelProperty("错误信息，兼容后端管理界面")
    public String getError(){
        if(this.code != HttpStatus.SUCCESS){
            return this.msg;
        }
        return null;
    }

}
